package net.bitdixit.ywu.library;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.Comparator;

import net.bitdixit.ywu.Util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;

public class Asana
{
	static public class Comprare implements Comparator<Asana> 
	{
		String lang;
		public Comprare(String lang)
		{
			this.lang = lang;
		}
		@Override
		public int compare(Asana arg0, Asana arg1) {
			return arg0.getName(lang).compareTo(arg1.getName(lang));
		}		
	}
	
	private AsanaLibrary library;
	private String name;
	private String name_eng;
	private String img;
	private String id;
	
	public String getId() {
		return id;
	}
	public String getName(String lang)
	{
		if (lang.equals(AsanaLibrary.LANG_SK)) return name;
		if (lang.equals(AsanaLibrary.LANG_EN)) return name_eng;
		return "";
	}
	public Asana(AsanaLibrary library, String id, String name, String name_eng, String img)
	{
		this.library = library;
		this.name = name;
		this.img = img;
		this.name_eng = name_eng;
		this.id  = id;
	}
	private File getCacheFile()
	{
		 if (Environment.getExternalStorageDirectory()==null)
			 return null;
		  
		  return new File(library.getContext().getExternalCacheDir().getAbsolutePath()+File.separator+
				  Base64.encodeToString(img.getBytes(), Base64.NO_WRAP));
		
	}
	public boolean isImageCached()
	{
		return getCacheFile().exists();
	}
	public Bitmap getImage() throws Exception
	{
		 byte[] data; 
		 File cacheFile=getCacheFile();
         if (cacheFile!=null && cacheFile.exists()) data=Util.readBytes(new FileInputStream(cacheFile));
         else
         {
        	 try
        	 {
        		 data = Util.readBytes(new URL(this.img).openStream());
        	 } catch (Exception e)
        	 {
        		 throw new Exception("Cannot download images from internet");
        	 }
         }

         if (cacheFile!=null && !cacheFile.exists())
         {
        	 cacheFile.getParentFile().mkdirs();
        	 new FileOutputStream(cacheFile).write(data);
         }

         return BitmapFactory.decodeByteArray(data, 0, data.length);
    }
}
